package com.anysoft.ui.activity.web;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.config.HostConstant;
import com.anysoft.manager.UserInfoManager;
import com.anysoft.model.AccountLoginEntity;
import com.anysoft.ui.activity.LoginActivity;
import com.anysoft.ui.activity.MentorHomeActivity;
import com.anysoft.ui.activity.MsMainHomeActivity;
import com.anysoft.ui.activity.ParentHomeActivity;
import com.anysoft.utils.ActivityCollector;
import com.anysoft.utils.LogUtil;
import com.anysoft.utils.NetWorkUtil;
import com.anysoft.utils.NewVersionUtils;
import com.anysoft.utils.StringUtil;
import com.anysoft.utils.ToastUtil;
import com.anysoft.widget.CustomWebView;
import com.anysoft.widget.HProgressBarLoading;
import com.anysoft.widget.MentorDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

/**
 * 游客页面
 */
public class TouristsActivity extends BaseActivity {
    
    private static final String TAG = "====>";
    @BindView(R.id.wv)
    public CustomWebView mWebView;
    @BindView(R.id.tv_item_web_error)
    public TextView tvItemWebError;
    @BindView(R.id.ll_item_web_error)
    public LinearLayout llItemWebError;
    @BindView(R.id.top_progress)
    public HProgressBarLoading top_progress;
    @BindView(R.id.rl_title_container)
    public RelativeLayout rl_title_container;
    @BindView(R.id.sdv_user_head)
    public SimpleDraweeView sdv_user_head;
    @BindView(R.id.tv_login_name)
    public TextView tv_login_name;
    @BindView(R.id.iv_share)
    public ImageView iv_share;
    
    public String loadUrl;
    public boolean isLoadError = false;
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webview, String url) {
            LogUtil.e(TAG, "shouldOverrideUrlLoading url=" + url);
            onshouldOverrideUrlLoadingCallBack(webview, url);
            return true;
        }
        
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            LogUtil.e(TAG, "onPageStarted " + url);
        }
        
        @Override
        public void onPageFinished(WebView view, String url) {
        }
        
        @Override
        public void onLoadResource(WebView view, String url) {
            LogUtil.e(TAG, "onLoadResource " + view.getProgress());
            super.onLoadResource(view, url);
        }
        
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            LogUtil.e(TAG, "onReceivedError" + view.getUrl());
            isLoadError = true;
            setShowErrorView(true);
            super.onReceivedError(view, request, error);
        }
        
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            LogUtil.e(TAG, "onReceivedHttpError" + view.getUrl());
            super.onReceivedHttpError(view, request, errorResponse);
        }
        
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();// 接受所有网站的证书   ，
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            top_progress.setCurProgress(newProgress);
        }
        
        @Override
        public boolean onJsAlert(final WebView view, String url, final String message, JsResult result) {
            result.confirm();//这里必须调用，否则页面会阻塞造成假死
            return true;
        }
        
        @Override
        public boolean onJsConfirm(final WebView view, String url, final String message, JsResult result) {
            LogUtil.e(TAG, "onJsConfirm:" + message);
            result.confirm();//这里必须调用，否则页面会阻塞造成假死
            return true;
        }
        
        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            LogUtil.e(TAG, "onJsPrompt:" + url);
            result.confirm();
            return true;
        }
    };
    private String androidApkUrl;
    private String newVersion;
    private String content;
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tourists_layout);
        ButterKnife.bind(this);
        setShowErrorView(false);
        iv_share.setVisibility(View.GONE);
        loadUrl = HostConstant.HOST_URL_H5_SERVER + "mainIndex.html";
        tvItemWebError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.setVisibility(View.GONE);
                llItemWebError.setVisibility(View.GONE);
                setWebViewConfig(loadUrl);
                
            }
        });
        
        if (NetWorkUtil.isConnect(this)) {
            setWebViewConfig(loadUrl);
        }
        getUpdateData("android");
    }
    
    public void setShowErrorView(boolean isLoadError) {
        if (isLoadError) {
            if (mWebView != null && llItemWebError != null) {
                llItemWebError.setVisibility(VISIBLE);
                mWebView.setVisibility(GONE);
            }
        } else {
            if (mWebView != null && llItemWebError != null) {
                llItemWebError.setVisibility(GONE);
                mWebView.setVisibility(VISIBLE);
            }
        }
    }
    
    /**
     * @param url
     */
    public void setWebViewConfig(String url) {
        if (mWebView == null || StringUtil.isEmpty(url)) {
            LogUtil.e("url不能为空 或者 webview不能为空");
            return;
        }
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setDisplayZoomControls(false);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(
                    WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webSettings.setAllowFileAccessFromFileURLs(true);
            webSettings.setAllowUniversalAccessFromFileURLs(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptThirdPartyCookies(mWebView, true);
        }
        
        // TODO: 2018/1/19 防止通过file域来恶意攻击
        if (url.startsWith("file://")) {
            webSettings.setAllowFileAccess(false);
            webSettings.setJavaScriptEnabled(false);
            webSettings.setAllowFileAccessFromFileURLs(false);
            webSettings.setAllowUniversalAccessFromFileURLs(false);
        } else {
            webSettings.setJavaScriptEnabled(true);
            webSettings.setAllowFileAccess(true);
        }
        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        //设置本地调用对象及其接口
//        mWebView.addJavascriptInterface(new JavaScriptObject(), "js_invoke");
        if (url.startsWith("http")) {
            mWebView.loadUrl(url);
        } else {
            mWebView.loadDataWithBaseURL("about:blank", url, "text/html", "UTF-8", null);
        }
        mWebView.setOnLoadFinishListener(new CustomWebView.OnLoadFinishListener() {
            @Override
            public void onLoadFinish() {
                pageFinished();
            }
        });
        mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
        mWebView.removeJavascriptInterface("accessibility");
        mWebView.removeJavascriptInterface("accessibiltyTraversal");
    }
    
    private void getUpdateData(String platform) {
        Map<String, String> params = new HashMap<>();
        params.put("platform", platform);
        OkGo.<String>post(HostConstant.UPDATE)
                .tag(this)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        getUpdateDataSuccess(response.body());
                    }
                    
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtil.showShort("服务器忙...");
                    }
                    
                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
        
    }
    
    private void pageFinished() {
        String title = null;
        if (mWebView != null)
            title = mWebView.getTitle();
        if (!isLoadError) {
            setShowErrorView(false);
        } else {
            isLoadError = false;
            setShowErrorView(true);
        }
        
        if (!StringUtil.isEmpty(title) && ("网页无法打开".equals(title) || title.contains("404"))) {
            setShowErrorView(true);
        }
    }
    
    private void getUpdateDataSuccess(String json) {
        try {
            JSONObject object = new JSONObject(json);
            int code = (int) object.get("code");
            if (code == 0) {
                androidApkUrl = (String) object.get("androidApkUrl");
                newVersion = (String) object.get("version");
                content = (String) object.get("content");
                NewVersionUtils.checkVersion(this, androidApkUrl, newVersion, content);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if (userInfoManager != null && !userInfoManager.needLogin()) {
            AccountLoginEntity accountLoginEntity = UserInfoManager.getInstance(this).getAccountLoginEntity();
            AccountLoginEntity.UserInfoBean userInfo = accountLoginEntity.getUserInfo();
            String showUserName = userInfo.getShowUserName();
            tv_login_name.setText(StringUtil.isEmpty(showUserName) ? "" : showUserName);
            String xingb = userInfo.getXingb();
            if ("男".equals(xingb)) {
                sdv_user_head.setImageResource(R.mipmap.ic_men_head);
            } else if ("女".equals(xingb)) {
                sdv_user_head.setImageResource(R.mipmap.ic_woman_head);
            } else {
                sdv_user_head.setImageResource(R.mipmap.ic_men_head);
            }
            // TODO: 2018/7/18 头像url还没有
            String touxiangUrl = userInfo.getTouxiangUrl();
        } else {
            sdv_user_head.setImageResource(R.mipmap.ic_user_head);
            tv_login_name.setText("登录");
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }
    
    private void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {
        webview.loadUrl(url);
    }
    
    @Override
    public void onBackPressed() {
        MentorDialog dialog = new MentorDialog(mActivity);
        dialog.setAnimationEnable(true);
        dialog.setCancelable(false);
        dialog.setTitle("提示");
        dialog.setContentText("确定要退出" + getResources().getString(R.string.app_name) + "吗？");
        dialog.setEditTextType(false);
        dialog.setNegativeListener("取消", new MentorDialog.OnNegativeListener() {
            @Override
            public void onClick(MentorDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.setPositiveListener("确认", new MentorDialog.OnPositiveListener() {
            @Override
            public void onClick(MentorDialog dialog) {
                dialog.dismiss();
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);
            }
        }).show();
    }
    
    @OnClick({R.id.iv_share, R.id.ll_tourists_login_container})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_share:
                ActivityCollector.startTargetActivity(this, DemoActivity.class);
                break;
            case R.id.ll_tourists_login_container:
                if (userInfoManager.needLogin()) {
                    ActivityCollector.startTargetActivity(this, LoginActivity.class);
                } else {
                    String userType = userInfoManager.getAccountLoginEntity().getUserInfo().getUserType();
                    if ("manager".equals(userType)) {
                        ActivityCollector.startTargetActivity(this, MsMainHomeActivity.class);
                    } else if ("mentor".equals(userType)) {
                        ActivityCollector.startTargetActivity(this, MentorHomeActivity.class);
                    } else if ("parent".equals(userType)) {
                        ActivityCollector.startTargetActivity(this, ParentHomeActivity.class);
                    }
                }
                break;
        }
    }
    
    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            //加载空内容
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.removeAllViews();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }
}
